Passing Arguments
C# Supports to pass the parameters in three ways they are

  1. Call by value or pass by value
  2. Call by reference or pass by reference.
  3. Call by out or Pass by out.

Call by Value
1) When then formal arguments are modified, if modifications are not reflected on actual arguments then that concept is called as call by value.

  1. By default all the variables are call by value.

 

 Call by Reference: (ref)
1) When then formal arguments are modified, if modifications are reflected on actual arguments then that concept is called as call by reference.

  1. Ref  is a keyword, which is required to pass a variable as a reference.
  2. Ref keyword must be used along with actual and formal arguments.
  3. Ref variables must be initialized before passing to the function.

 

Program on Call by reference
using System;
class abc
{

    public void put(ref int x)
{
Console.WriteLine("Value of x" + x);
x = 80;
}

}
class sample
{
public static void Main()
{
int a = 10;
abc x = new abc();
x.put(ref a);
Console.WriteLine("After CAll by refernce" + a);
}
}

Program to find the Factorial value using call by reference

using System;
class abc
{

 
public void fact(int x,ref int f)
{

        while (x >= 1)
{
f = f * x;
x--;
}

    }

}
class sample
{
public static void Main()
{
int f = 1,a;
Console.WriteLine("Enter number");
a = Convert.ToInt32(Console.ReadLine());
abc x = new abc();
x.fact(a,ref f);
Console.WriteLine("Factorial value" + f);
}
}

Out parameter

  1. An out parameter is similar to a ref parameter.
  2. Out is a keyword
  3. The variables passing as out are not required to be initialize
  4. Even if it is initialized, the value will not be passed
  5. Out=ref-initialization

Program on out parameter
using System;
class abc
{

    public void put(int x,int y,out int z)
{
z=x+y;
}

   
}
class sample
{
public static void Main()
{
int a,b,c;
Console.WriteLine ("Enter 2 numbers");
a=Convert.ToInt32 (Console.ReadLine ());
b=Convert.ToInt32 (Console.ReadLine ());
abc x=new abc();
x.put (a,b,out c);
Console.WriteLine ("Sum"+c);
}
}

 

 

Program on Array as a parameter
using System;

class abc
{

    public void put(int [] x)
{
for (int i = 0; i < x.GetLength(0) ; i++)
{
Console.WriteLine(x[i]);
x[i] = x[i] * 2;
}

 

    }
}
class sample
{
public static void Main()
{
int []a={10,20,30,40};

abc x=new abc ();
x.put(a);
Console.WriteLine();
foreach (int k in a)
Console.WriteLine (k);

}
}